﻿using IV.Core;
using IV.Core.Data;
using IV.Core.Interfaces;
using Microsoft.Win32;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace IV.Components.Log
{
    public class LogComponent : BindableBase
    {
        public LogComponent()
        {
            MakeUpCommands();
        }
        public void Initialize()
        {
            // 注册视图
            var regionManager = CommonServiceLocator.ServiceLocator.Current.GetInstance<IRegionManager>();
            regionManager.RegisterViewWithRegion(AppConstants.Region_HomeLog, typeof(LogControl));
            regionManager.RegisterViewWithRegion(AppConstants.Region_LogConponent, typeof(LogControl2));
            LogHelper.LogInstance.LogEvent += LogInstance_LogEvent;
            ViewLogMaxCount = Math.Max(1, AppSettings.LocalSettings.GetScope("LogView").Default("ViewLogMaxCount", 1000).Value<int>("ViewLogMaxCount"));
        }

        int ViewLogMaxCount;
        private void LogInstance_LogEvent(LogItem log)
        {
            Application.Current?.Dispatcher.BeginInvoke(new Action(() => 
            {
                LogItems.Add(log); 
                if(LogItems.Count > ViewLogMaxCount)
                {
                    LogItems = new ObservableCollection<LogItem>(LogItems.Skip(ViewLogMaxCount / 2));
                }
            }));
        }

        public ObservableCollection<LogItem> LogItems
        {
            get => _LogItems;
            set => SetProperty(ref _LogItems, value);
        }
        private ObservableCollection<LogItem> _LogItems = new ObservableCollection<LogItem>();

        #region commands
        void MakeUpCommands()
        {
            CleareLogCommand = new DelegateCommand(OnCleareLogCommand);
            ExportLogCommand = new DelegateCommand(OnExportLogCommand);
        }
        /// <summary>
        /// 清空
        /// </summary>
        public DelegateCommand CleareLogCommand { get; private set; }
        private void OnCleareLogCommand()
        {
            LogItems.Clear();
        }
        /// <summary>
        /// 导出
        /// </summary>
        public DelegateCommand ExportLogCommand { get; private set; }
        private void OnExportLogCommand()
        {
            var dialog = new SaveFileDialog();
            dialog.Filter = "TXT File|*.txt";
            dialog.FileName = DateTime.Now.ToString("yyyy-MM-dd_HHmmss");
            dialog.RestoreDirectory = true;
            if (dialog.ShowDialog() == true)
            {
                try
                {
                    ExportLog(dialog.FileName);
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
        #endregion

        private void ExportLog(string filename)
        {
            var fStream = File.Create(filename);
            var list = new List<LogItem>(LogItems);
            foreach (var item in list)
            {
                var logBytes = Encoding.Default.GetBytes($"{item}\r\n");
                fStream.Write(logBytes, 0, logBytes.Length);
            }
            fStream.Flush();
            fStream.Close();
        }
    }
}
